package com.lytoyo.neihanduanzi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lytoyo.neihanduanzi.mapper.StatusMapper;
import com.lytoyo.neihanduanzi.mapper.UserMapper;
import com.lytoyo.neihanduanzi.model.Result;
import com.lytoyo.neihanduanzi.model.dto.StatusDto;
import com.lytoyo.neihanduanzi.model.user.UserInfo;
import com.lytoyo.neihanduanzi.model.vo.UserInfoVo;
import com.lytoyo.neihanduanzi.service.UserService;
import com.lytoyo.neihanduanzi.utils.Constant;
import com.lytoyo.neihanduanzi.utils.MD5Utils;
import com.lytoyo.neihanduanzi.utils.VerCodeGenerateUtil;
import jakarta.annotation.Resource;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Package:com.lytoyo.neihanduanzi.service.impl
 *
 * @ClassName:UserServiceImpl
 * @Create:2025/1/9 19:32
 **/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private JavaMailSenderImpl javaMailSender;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private StatusMapper statusMapper;

    @Override
    public void getVerCode(String email) {
        MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
        try{
            //生成6位验证码
            String verCode = VerCodeGenerateUtil.getVerCode();
            //存入内存
            redisTemplate.opsForValue().set(Constant.VERCODE_KEY+email,verCode,Constant.VERCODE_TTL, TimeUnit.MINUTES);
            //生成邮件
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(new InternetAddress(this.javaMailSender.getUsername(), "内涵段子"));
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setSubject("【内涵段子】邮箱注册验证");
            String emailContent = "<html>" +
                    "<body>" +
                    "<h2>尊敬的用户，您好！</h2>" +
                    "<p>感谢您注册【内涵段子】平台。为确保您的账户安全，请使用以下验证码完成邮箱验证：</p>" +
                    "<p style='font-size: 24px; font-weight: bold;'>验证码: <span style='color: #ff5722; text-decoration: underline; cursor: pointer;'>" + verCode + "</span></p>" +
                    "<p>该验证码有效期为 5 分钟，请尽快完成验证。</p>" +
                    "<p>如果您未申请注册，请忽略本邮件。</p>" +
                    "<p>感谢您的支持与信任！</p>" +
                    "<p>【内涵段子】团队</p>" +
                    "</body>" +
                    "</html>";
            mimeMessageHelper.setText(emailContent,true);
            //发送邮件
            this.javaMailSender.send(mimeMessage);
            log.info("mimeMessage:{}",mimeMessage);
        }catch (Exception var7) {
            var7.printStackTrace();
        }
    }

    @Override
    public Result regist(UserInfo userInfo, String code) {
        //将密码做加密处理
        userInfo.setPassword(MD5Utils.code(userInfo.getPassword()));
        //判断密码是否为空
        if(null != userInfo.getPhone()){
            return Result.fail(-1,"密码不能为空");
        }
        //获取缓存中的验证码
        String vercode = (String) redisTemplate.opsForValue().get(Constant.VERCODE_KEY + userInfo.getEmail());
        //判断验证码是否为空，为空代表已经过期
        if(null == vercode){
            return Result.fail(-1,"验证码已过期");
        }
        //判断前端验证码是否与缓存验证码相同
        if (!vercode.toUpperCase().equals(code)){
            return Result.fail(-1,"验证码错误，请重试");
        }
        //查看数据库中是否存在用户，如果存在则不可注册
        UserInfo user = this.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getEmail, userInfo.getEmail()));
        if(null != user){
            return Result.fail(-1,"用户已存在，不可重复注册");
        }
        String nickname = "段友"+UUID.randomUUID().toString().replaceAll("-", "").substring(0,6);
        userInfo.setNickname(nickname);
        userInfo.setGender(1);
        userInfo.setHeadPhoto("https://lpyx-oss-storage.oss-cn-guangzhou.aliyuncs.com/v2-f794962ce3244dac5dc19dc021958c3e_r.png");
        this.save(userInfo);
        //异步处理
        rabbitTemplate.convertAndSend(Constant.EXCHANGE_DIRECT_NEIHANDUANZI_STATUS,Constant.ROUTING_KEY_NEIHANDUANZI_STATUS,userInfo.getId());
        return Result.success("");
    }

    @Override
    public Map<String, Object> requestStatus(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        //粉丝
        CompletableFuture fansCompletableFuture = CompletableFuture.runAsync(() -> {
            StatusDto statusDto = statusMapper.selectOne(new LambdaQueryWrapper<StatusDto>().eq(StatusDto::getUserId, userId).eq(StatusDto::getType,"0701"));
            map.put("fans",statusDto.getAmount());
        }, threadPoolExecutor);
        //关注
        CompletableFuture attentionCompletableFuture = CompletableFuture.runAsync(() -> {
            StatusDto statusDto = statusMapper.selectOne(new LambdaQueryWrapper<StatusDto>().eq(StatusDto::getUserId, userId).eq(StatusDto::getType,"0702"));
            map.put("attention",statusDto.getAmount());
        }, threadPoolExecutor);
        //获赞
        CompletableFuture likeCompletableFuture = CompletableFuture.runAsync(() -> {
            StatusDto statusDto = statusMapper.selectOne(new LambdaQueryWrapper<StatusDto>().eq(StatusDto::getUserId, userId).eq(StatusDto::getType,"0703"));
            map.put("liked",statusDto.getAmount());
        }, threadPoolExecutor);
        //多任务组合
        CompletableFuture.allOf(fansCompletableFuture,attentionCompletableFuture,likeCompletableFuture).join();

        return map;
    }

    /**
     * 获取目标用户的详细信息
     * @param userId
     * @return
     */
    @Override
    public Result otherImfor(Long userId) {
        UserInfo userInfo = this.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        if(null == userInfo) return Result.fail(-1,"用户已注销");
        BeanUtils.copyProperties(userInfo,userInfoVo, UserInfoVo.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",userInfoVo);
        //粉丝
        CompletableFuture fansCompletableFuture = CompletableFuture.runAsync(() -> {
            StatusDto statusDto = statusMapper.selectOne(new LambdaQueryWrapper<StatusDto>().eq(StatusDto::getUserId, userId).eq(StatusDto::getType,"0701"));
            map.put("fans",statusDto.getAmount());
        }, threadPoolExecutor);
        //关注
        CompletableFuture attentionCompletableFuture = CompletableFuture.runAsync(() -> {
            StatusDto statusDto = statusMapper.selectOne(new LambdaQueryWrapper<StatusDto>().eq(StatusDto::getUserId, userId).eq(StatusDto::getType,"0702"));
            map.put("attention",statusDto.getAmount());
        }, threadPoolExecutor);
        //获赞
        CompletableFuture likeCompletableFuture = CompletableFuture.runAsync(() -> {
            StatusDto statusDto = statusMapper.selectOne(new LambdaQueryWrapper<StatusDto>().eq(StatusDto::getUserId, userId).eq(StatusDto::getType,"0703"));
            map.put("liked",statusDto.getAmount());
        }, threadPoolExecutor);
        //多任务组合
        CompletableFuture.allOf(fansCompletableFuture,attentionCompletableFuture,likeCompletableFuture).join();
        return Result.success(map);
    }


}
